package com.tancire.sources.service.impl;

import com.tancire.common.core.domain.model.LoginUser;
import com.tancire.common.exception.ResourceException;
import com.tancire.common.utils.DateUtils;
import com.tancire.common.utils.SecurityUtils;
import com.tancire.common.utils.file.FileUtils;
import com.tancire.file.bean.SaveFileBean;
import com.tancire.file.service.ISysFileService;
import com.tancire.member.domain.Member;
import com.tancire.member.service.IMemberService;
import com.tancire.sources.domain.*;
import com.tancire.sources.mapper.SurResourceDetailMapper;
import com.tancire.sources.mapper.SurResourceMapper;
import com.tancire.sources.service.ISurResourceDetailService;
import com.tancire.sources.utils.WriteFileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.List;

/**
 * 资源明细Service业务层处理
 *
 * @author chenchao
 * @date 2024-07-05
 */
@Slf4j
@Service
public class SurResourceDetailServiceImpl implements ISurResourceDetailService {

    @Resource
    private SurResourceDetailMapper surResourceDetailMapper;

    @Resource
    private SurResourceMapper surResourceMapper;

    @Resource
    private IMemberService memberService;

    @Resource
    private ISysFileService sysFileService;

    @Resource
    private WriteFileUtils writeFileUtils;

    /**
     * 查询资源明细
     *
     * @param id 资源明细主键
     * @return 资源明细
     */
    @Override
    public SurResourceDetail selectSurResourceDetailById(Long id) {
        return surResourceDetailMapper.selectSurResourceDetailById(id);
    }

    /**
     * 查询资源明细列表
     *
     * @param surResourceDetail 资源明细
     * @return 资源明细
     */
    @Override
    public List<SurResourceDetail> selectSurResourceDetailList(SurResourceDetail surResourceDetail) {
        return surResourceDetailMapper.selectSurResourceDetailList(surResourceDetail);
    }

    /**
     * 新增资源明细
     *
     * @param surResourceDetail 资源明细
     * @return 结果
     */
    @Override
    public int insertSurResourceDetail(SurResourceDetail surResourceDetail) {
        surResourceDetail.setCreateTime(DateUtils.getNowDate());
        if (null != surResourceDetail.getResourceId()) {
            this.handleBaseData(surResourceDetail);
        }
        int sort = this.getLastSort(surResourceDetail.getResourceId());
        surResourceDetail.setFileSort(sort);
        return surResourceDetailMapper.insertSurResourceDetail(surResourceDetail);
    }

    /**
     * 初始化基础数据
     *
     * @param surResourceDetail
     */
    private void handleBaseData(SurResourceDetail surResourceDetail) {
        // 初始化基础信息
        Long resourceId = surResourceDetail.getResourceId();
        if (null == resourceId) {
            throw new ResourceException("资源ID不能为空");
        }
        SurResource surResource = surResourceMapper.selectSurResourceById(resourceId);
        if (null == surResource) {
            throw new ResourceException("未查询到对应资源");
        }
        // 获取后缀名
        String extName = FileUtils.getFileExtName(surResourceDetail.getFilePath());
        surResourceDetail.setFileType(extName);
    }

    /**
     * 修改资源明细
     *
     * @param surResourceDetail 资源明细
     * @return 结果
     */
    @Override
    public int updateSurResourceDetail(SurResourceDetail surResourceDetail) {
        surResourceDetail.setUpdateTime(DateUtils.getNowDate());
        this.handleBaseData(surResourceDetail);
        return surResourceDetailMapper.updateSurResourceDetail(surResourceDetail);
    }

    /**
     * 批量删除资源明细
     *
     * @param ids 需要删除的资源明细主键
     * @return 结果
     */
    @Override
    public int deleteSurResourceDetailByIds(Long[] ids) {
        return surResourceDetailMapper.deleteSurResourceDetailByIds(ids);
    }

    /**
     * 删除资源明细信息
     *
     * @param id 资源明细主键
     * @return 结果
     */
    @Override
    public int deleteSurResourceDetailById(Long id) {
        return surResourceDetailMapper.deleteSurResourceDetailById(id);
    }

    /**
     * 获取视频授权码
     *
     * @param id
     * @return
     */
    @Override
    public SourceCode getViewCode(Long id, boolean open) {
        SourceCode res = new SourceCode();
        res.setAuthStatus(0);
        SurResourceDetail surResourceDetail = this.surResourceDetailMapper.selectSurResourceDetailById(id);
        Integer memberVip = surResourceDetail.getMemberVip();
        // 其他校验等
        if (null != memberVip && 1 == memberVip) {
            if (open) {
                res.setAuthStatus(1);
                res.setMsg("当前视频为会员专享视频，请先登录账号后观看");
                return res;
            } else {
                // 校验用户是否是会员
                LoginUser loginUser = this.getLoginUser();
                if (null == loginUser) {
                    res.setAuthStatus(1);
                    res.setMsg("当前视频为会员专享视频，请先登录账号后观看");
                    return res;
                }
                Member member = memberService.selectMemberByMemberId(loginUser.getUserId());
                Integer memberVips = member.getMemberVip();
                if (null == memberVips || 1 != memberVips) {
                    res.setAuthStatus(2);
                    res.setMsg("当前视频为会员专享视频，请先开通会员后观看");
                    return res;
                }
            }
        }
        // 生成code
        String code = writeFileUtils.generateCode(surResourceDetail.getId());
        res.setAuthCode(code);
        return res;
    }

    private LoginUser getLoginUser() {
        try {
            return SecurityUtils.getLoginUser();
        } catch (Exception e) {
            // 获取失败不处理
        }
        return null;
    }

    @Override
    public void view(String code, HttpServletRequest req, HttpServletResponse res) {
        log.info("进入视频流接口");
        SourceAuth sourceAuth = writeFileUtils.checkAuth(code);
        SurResourceDetail surResourceDetail = this.surResourceDetailMapper.selectSurResourceDetailById(sourceAuth.getId());
        writeFileUtils.view(new WriteFile(surResourceDetail.getFileName(), surResourceDetail.getFilePath(), surResourceDetail.getFileSize(), surResourceDetail.getFileType()), req, res);
    }

    /**
     * 获取资源明细列表
     *
     * @param resourceId
     * @return
     */
    @Override
    public List<SurResourceDetail> listByResourceId(Long resourceId) {
        if (null == resourceId) {
            return Collections.emptyList();
        }
        SurResourceDetail query = new SurResourceDetail();
        query.setResourceId(resourceId);
        return surResourceDetailMapper.selectSurResourceDetailList(query);
    }

    /**
     * 下载文件
     *
     * @param code
     * @param req
     * @param res
     */
    @Override
    public void download(String code, HttpServletRequest req, HttpServletResponse res) {
        SourceAuth sourceAuth = writeFileUtils.checkAuth(code);
        SurResourceDetail surResourceDetail = this.surResourceDetailMapper.selectSurResourceDetailById(sourceAuth.getId());
        writeFileUtils.write(new WriteFile(surResourceDetail.getFileName(), surResourceDetail.getFilePath(), surResourceDetail.getFileSize(), surResourceDetail.getFileType()), res);

    }

    @Override
    public SaveFileBean uploadFile(MultipartFile file, Long resourceId) {
        try {
            SaveFileBean saveFileBean = sysFileService.uploadFile(file, "Y");
            String fileName = saveFileBean.getFileName();
            int sort = this.getLastSort(resourceId);
            // 初始化数据库保存数据
            SurResourceDetail surResourceDetail = new SurResourceDetail();
            surResourceDetail.setFilePath(fileName);
            surResourceDetail.setResourceId(resourceId);
            surResourceDetail.setFileSize(saveFileBean.getFileSize());
            surResourceDetail.setFileName(FileUtils.getNameNotSuffix(fileName));
            surResourceDetail.setFileType(FileUtils.getFileExtName(fileName));
            surResourceDetail.setFileSort(sort);
            this.surResourceDetailMapper.insertSurResourceDetail(surResourceDetail);
            return saveFileBean;
        } catch (Exception e) {
            throw new ResourceException("上传资源文件异常");
        }
    }

    /**
     * 查询最后一个的索引
     *
     * @param resourceId
     * @return
     */
    private int getLastSort(Long resourceId) {
        SurResourceDetail last = this.surResourceDetailMapper.selectLastOne(resourceId);
        if (null != last) {
            Integer fileSort = last.getFileSort();
            if (null == fileSort) {
                return 1;
            }
            return fileSort + 1;
        }
        return 1;
    }

    private Long getUserId() {
        try {
            return SecurityUtils.getUserId();
        } catch (Exception e) {
            // 不处理
        }
        return null;
    }
}
